<template>
	<view class="" style="width: 100vw;height: 100vh" :style="{'background':kbackgroundColor}">
		<hx-navbar title="个人信息" :back="true" :fixed="false" :color="knavTitleColor" barPlaceholder="hidden"
			transparent="auto"></hx-navbar>
		<view class="content" :style="{color:knormalColor}" style="margin-top:150rpx;">
			<view class="" style="padding-bottom: 80px;">
				<view class="cont-box"  :style="{background:kcellBgColor}">
					<view class="avatar_box" @click="uploadAvatar()">
						<image class="avatar" v-if="info.avatar && info.avatar.includes('http')" :src="info.avatar"
							@error="avatarDefaultImage()" mode="aspectFill"></image>
						<image class="avatar" v-if="!info.avatar" src="../../../logo.png" mode="aspectFill"></image>
						<image class="avatar" v-if="(info.avatar && !info.avatar.includes('http'))" src="../../../logo.png"
							mode="aspectFill"></image>
					</view>
					<view class="settings_item" @click="$common.navigateTo('/pages/user/settings/userInfo/userInfo')">
						<view class="settings_name">昵称</view>
						<view class="flex1 value">{{info.nickname}}</view>
						<n-icon name="right" size="19" :color="ktheme =='black' ? '#fff':'#333'"></n-icon>
					</view>
					<view class="settings_item">
						<view class="settings_name">手机号</view>
						<view class="value">{{account.phone}}</view>
					</view>
					<!-- #ifdef APP-PLUS || APP-PLUS-NVUE -->
					<view class="settings_item">
						<view class="settings_name">微信</view>
						<view class=" value" v-if='account.bound' @click="relieveCheck()">{{account.nickname}}</view>
						<view class=" value" v-else @click="Bindingwx">未绑定</view>
						<image src="@/static/user/menu_icon/wx.png"
							style="margin-left: 5rpx;width: 33rpx;height: 31rpx;" mode=""></image>
					</view>
					<!-- #endif -->
				</view>
				<view class="cont-box m-t-20" :style="{background:kcellBgColor}">
					<view class="settings_item" v-for="item,id in menu_list" :key="id" @tap="navto(item.url,item.id)">
						<view class="settings_name flex1">{{item.name}}</view>
						<view class="text cell-item-ft" v-if="item.id==2">
							<view class="code">
								<text v-if="info.chainAddress">{{info.chainAddress }}</text>
								<text v-else>***实名后自动生成***</text>
							</view>
							<uni-icons v-if="info.chainAddress" @tap="copy(info.chainAddress)" type="paperclip" size="19" :color="ktheme =='black' ? '#fff':'#333'"></uni-icons>
						</view>
						<view class="apply cell-item-ft" v-if="item.id==3">
							<!-- <image class="apply-img"
								:src="!info.isCertified?'/static/user/apply-img.png':'/static/user/apply-img2.png'"
								mode="widthFix"></image> -->
							<image class="apply-img" v-if="account.isCertified && ktheme == 'black'"
								src="/static/user/user-authed.png" mode="widthFix"></image>
							<image class="apply-img" v-if="account.isCertified && ktheme == 'purple'"
								src="/static/user/apply-img-white.png" mode="widthFix"></image>
							<image class="apply-img" v-if="!account.isCertified" src="/static/user/apply-img2.png"
								mode="widthFix"></image>
						</view>
						<block v-if="item.id!=2">
							<n-icon name="right" size="19" :color="ktheme =='black' ? '#fff':'#333'"></n-icon>
						</block>
					</view>
				</view>
				<view>
					<!-- 提示窗示例 -->
					<uni-popup ref="alertDialog" type="dialog">
						<uni-popup-dialog type="info" cancelText="关闭" confirmText="复制" title="区块链地址"
							@confirm="dialogConfirm" @close="dialogClose">
							<view class=""
								style="overflow-wrap: break-word;word-wrap: break-word;width:510rpx;height: 120rpx;line-height: 1.6;">
								{{info.kmsId}}
							</view>
						</uni-popup-dialog>
					</uni-popup>
				</view>
				<!-- 	<view class="cont-box m-t-20">
					<view class="settings_item" @click="logOff">
						<view class="settings_name flex1">
							注销账号
						</view>
						<n-icon name="right" size="19" color="#333"></n-icon>
					</view>
				</view>
			 -->
			</view>

			<view class="logout" :style="{background:kbuttonBgColor,color:knavgroundColor}" @click="tui">退出账号</view>
		</view>
		<uni-popup ref="bindingDialog" type="center" :maskBackgroundColor="'rgba(0,0,0,0.5)'"
			:isMaskClick="false">
			<view class="store-view store-border-all tips-padding"
				:style="{'background':kbackgroundColor,color:knormalColor}"
				:class="[{'alert-border-black alert-border-shadow-black':ktheme =='black'},{'alert-border-purple':ktheme =='purple'}]">
				<text class="popup-title">提示</text>
				<text class="popup-subtitle">确认退出登录吗?</text>
				<view class="tips-bottom">
					<view class="tips-button"
						:class="[{'tips-cancel-bg-black':ktheme =='black'},{'tips-cancel-bg-white':ktheme =='purple'}]"
						@click="bindingClose()">关闭</view>
					<view class="tips-button" :style="{background:kbuttonBgColor}" @click="bindingCheck()">确认
					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="confirmDialog" type="center" :maskBackgroundColor="'rgba(0,0,0,0.5)'" :isMaskClick="false">
			<view class="store-view store-border-all tips-padding"
				:style="{'background':kbackgroundColor,color:knormalColor}"
				:class="[{'alert-border-black alert-border-shadow-black':ktheme =='black'},{'alert-border-purple':ktheme =='purple'}]">
				<text class="popup-title">提示</text>
				<text class="popup-subtitle">如果解绑微信将无法继续使用它登录金世界，确定解绑吗</text>
				<view class="tips-bottom">
					<view class="tips-button"
						:class="[{'tips-cancel-bg-black':ktheme =='black'},{'tips-cancel-bg-white':ktheme =='purple'}]"
						@click="colfirmClose()">关闭</view>
					<view class="tips-button" :style="{background:kbuttonBgColor}" @click="relieveWx()">确定解绑
					</view>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		apiBaseUrl
	} from '@/config/config.js';
	export default {
		data() {
			return {
				wxnickname: "",
				selStyle: {
					'--selectColorSize': this.$store.state.selectColorSize, //字体选中颜色
					'--selBcakborder': this.$store.state.selBcakborder, //选中背景线颜色
					'--QianmenonlyBackgournd': this.$store.state.QianmenonlyBackgournd, //浅色单个背景颜色
					'--onlyBackgournd': this.$store.state.onlyBackgournd, //单个背景颜色
					'--borderSty': this.$store.state.borderSty, //边框颜色
				},
				avatar: '',
				mobile: '',
				nickname: '',
				menu_list: [
					// {
					// 	id: 1,
					// 	name: '绑定银行卡',
					// 	icon: "/static/user/settings_icon/icon_set_2.png",
					// 	url: '/pages/user/settings/bank/bank'
					// },
					// {
					// 	id: 7,
					// 	name: '设置支付宝账号',
					// 	icon: "/static/user/settings_icon/icon_set_7.png",
					// 	url: '/pages/user/settings/wechat/wechat?type=4'
					// },

					// {
					// 	id: 3,
					// 	name: '修改登录密码',
					// 	icon: "/static/user/settings_icon/icon_set_3.png",
					// 	url: '/pages/user/settings/forget/forget'
					// },

					{
						id: 2,
						name: '区块链地址',
						// icon: "/static/user/settings_icon/icon_set_4.png",
						url: 'lian'
					}, {
						id: 3,
						name: '我的认证',
						// icon: "/static/user/settings_icon/icon_set_4.png",
						url: '/pages/user/apply/apply'
					}, {
						id: 4,
						name: '设置交易密码',
						// icon: "/static/user/settings_icon/icon_set_3.png",
						url: '/pages/user/settings/pay_pass/pay_pass'
					},
				],
				info: {},
				account: {}
			}
		},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh()
			}, 1000)
			var _this = this;
			_this.$api.userInfo({}, function(res) {
				if (res.status) {
					var reg = /(\d{3})\d{4}(\d{4})/; //正则表达式
					res.data.mobile = res.data.mobile.replace(reg, "$1****$2")
					_this.nickname = res.data.nickname;
					_this.mobile = res.data.mobile || '暂无手机号';
					_this.avatar = res.data.avatar;
					_this.info = res.data
					if (res.data.username) {
						_this.username = res.data.username;
					} else {
						_this.username = "暂无用户名"
					}

				} else {
					//报错了
					_this.$common.errorToShow(res.msg);
				}
			});
		},
		onShow: function() {
			this.requestUserInfo()
			this.userAccount()
		},
		onLoad() {},
		methods: {
			userAccount() {
				this.$api.userAccount({}, res => {
					if (res.status) {
						this.account = res.data
					}
				})
			},
          	requestUserInfo() {
				var _this = this;
				_this.$api.userInfo({}, function(res) {
					if (res.status) {
						_this.info = res.data
					}
				});

			},

			//绑定微信
			Bindingwx() {
				var _this=this
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						let token = _this.$db.get("userToken");
						var data = {
							code: code
						}
						//客户端成功获取授。权临时票据（code）,向业务服务器发起登录请求。
						_this.$api.appboundWeixin(data, res => {
							if (res.status) {
								_this.userAccount()
									_this.$common.errorToShow('绑定成功');
							} else {
								_this.$common.errorToShow(res.message);
							}
						})

					},
					fail: function(err) {
						_this.$common.errorToShow(err);

					}
				  })
			},
			// 关闭
			colfirmClose() {
				this.$refs.confirmDialog.close()
			},

			//解除绑定微信
			relieveCheck() {
				this.$refs.confirmDialog.open()
			},
			// 关闭
			bindingClose() {
				this.$refs.bindingDialog.close()
			},
			
			bindingCheck() {
				var data={
					token:this.$db.get("userToken")
				}
				this.$api.signout(data,res=>{
						this.$db.del('userToken')
						uni.reLaunch({
							url: '/pages/login/login'
						})
				 
				
				})
			
			},
			relieveWx() {
				var _this = this
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						let token = _this.$db.get("userToken");
						var data = {
							code: code
						}
						//客户端成功获取授。权临时票据（code）,向业务服务器发起登录请求。
						_this.$api.apprelieveWeixin(data, res => {
							if (res.status) {
								_this.userAccount()
							} else {
								_this.$common.errorToShow(res.message);
							}
							_this.$refs.confirmDialog.close()
						})

					},
					fail: function(err) {
						_this.$common.errorToShow(err);
					}
				})
			},

			avatarDefaultImage() {
				this.info.avatar = '../../static/logo.png'
			},
			tui() {
				this.$common.modelShow('退出', '确认退出登录吗?', () => {
					this.$db.del('userToken')
					uni.removeStorageSync('invite_way');
					uni.reLaunch({
						url: '/pages/login/login'
					})
				})
			},
			logOff() {
				this.$common.modelShow('注销', '确认注销账户吗?', () => {
					this.$api.upCancel({}, res => {
						if (res.status) {
							this.$common.successToShow(res.msg)
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					})
				})
			},
			// 用户上传头像
			uploadAvatar() {
				let _this = this
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						let filePath = tempFilePaths[0]
						//#ifdef APP-IOS || APP-ANDROID
						const theme = uni.getStorageSync('theme');
						let color = theme == 'purple' ? "#000000" : "#ffffff"
						let style = theme == 'purple' ? "black" : "white"
						var styles = {
							color: color,
							background: "rgba(0,0,0,0.0)",
							style: style,
						}
						var waiting = plus.nativeUI.showWaiting("上传中...", styles);
						_this.uploadFile(filePath)
						//#endif
						// #ifndef APP-IOS || APP-ANDROID
						uni.showLoading({
							title: '上传中...'
						});
						_this.afterRead(tempFilePaths)
						// #endif
					}
				});
			},
			//压缩
			recursionCompressH5(url) {
				return new Promise((resolve, reject) => {
					this.recursionCompress(url, resolve)
				})
			},
			// 传入blob路径，.then()获取blob文件
			httpRequest(src) {
				let that = this
				return new Promise((resolve, reject) => {
					let xhr = new XMLHttpRequest()
					xhr.open('GET', src, true)
					xhr.responseType = 'blob'
					xhr.onload = function(e) {
						if (this.status == 200) {
							let myBlob = this.response
							let files = new window.File(
								[myBlob],
								myBlob.type, {
									type: myBlob.type
								}
							) // myBlob.type 自定义文件名
							resolve(files)
						} else {
							reject(false)
						}
					}
					xhr.send()
				})
			},
			recursionCompress(url, resolve) {
				let _this = this
				uni.getImageInfo({
					src: url,
					success(res) {
						let canvasWidth = res.width; //图片原始长宽
						let canvasHeight = res.height;
						let img = new Image();
						img.src = res.path;
						let canvas = document.createElement("canvas");
						let ctx = canvas.getContext("2d");
						canvas.width = canvasWidth / 2;
						canvas.height = canvasHeight / 2;
						ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
						canvas.toBlob(function(fileSrc) {
							let imgSrc = window.URL.createObjectURL(fileSrc);
							uni.getFileInfo({
								filePath: imgSrc,
								success: (resFileInfo) => {
									console.log(imgSrc, 'resFileInfo', resFileInfo)
									if (resFileInfo.size > 1024 * 1024) {
										//压缩后大于1M就继续压缩
										console.log('再次压缩')
										_this.recursionCompress(imgSrc, resolve);
										// indexObj.recursionCompressH5(imgSrc, callback, item);
										return;
									} else {
										resolve(imgSrc)
									}
								},
							});
						});
					}
				});
			},
			afterRead(e) {
				let _this = this
				const file = e
				console.log("e", e)
				// 遍历图片资源
				file.map(item => {
					console.log(item, 'item')
					// 进行压缩图片
					this.recursionCompressH5(item).then(url => {
						console.log(url, 'url')
						_this.httpRequest(url).then(res => {
							console.log(res, '成功转换为blob文件');
							const fileReader = new FileReader()
							fileReader.readAsDataURL(
									res
									) // 读取blob类型的图像文件（不是blob路径），读取成功触发onload方法，并得到result（base64格式的图片）
							fileReader.onload = (event) => {
								console.log(fileReader.result, 'fileReader.result - base64格式');
								if (fileReader.result) {
									// 上传最终压缩之后的图片
									_this.uploadFile(fileReader.result).then(res => {
										// uni.hideLoading();
										console.log(res)
										// this.fileList.push(res)
									}).catch(() => {
										//#ifdef APP-PLUS
										plus.nativeUI.closeWaiting();
										//#endif
										uni.hideLoading();
									})
									// 调用wx_uploadImage接口，图片大小必须是1M以下，否则报错
									// wx_uploadImage({
									//   image: fileReader.result
									// }).then(res => {
									//   console.log('上传图片成功', res)
									//   this.image = res.storage_path
									// })
								}
							}
						})
					})
				})
			},
			uploadFile(path) {
				let _this = this
				let url = apiBaseUrl + 'mfh/updateHead/' + _this.info.uid
				let token = this.$db.get('userToken')
				const uploadTask = uni.uploadFile({
					url: url,
					filePath: path,
					fileType: 'image',
					name: 'file',
					header: {
						// 'Content-Type': 'multipart/form-data',
						'Authorization': 'Bearer ' + token
					},
					success: (res) => {
						console.log('完成' + JSON.stringify(res))
						let data = JSON.parse(res.data);
						if (data.status) {
							_this.$common.successToShow('头像上传完成')
							_this.requestUserInfo()
						} else {
							if (data.message) {
								_this.$common.errorToShow(data.message)
							}
						}
					},
					fail: (error) => {
						if (error && error.message) {
							_this.$common.errorToShow(res.message)
						}
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					},
					complete: () => {
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					}
				});
			},
			navto: function(url, id) {
				uni.navigateTo({
					url: url
				})
			},
			copyClick() {
				this.$refs.alertDialog.open()
			},
			dialogConfirm() {

				let that = this
				uni.setClipboardData({
					data: this.info.kmsId,
					success() {
						that.$common.errorToShow('已复制剪贴板')
					},
					fail(r) {
						console.log(r)
					}
				})
			},
			dialogClose() {
				console.log('点击关闭')
			},
			copy: function(contnet) {

				let that = this
				if (!contnet) {
					this.$common.errorToShow('未取得区块链地址');
					return;
				}
				uni.setClipboardData({
					data: contnet,
					success() {
						that.$common.errorToShow('已复制剪贴板')
					},
					fail(r) {
						console.log(r)
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	@import url('/pages/user/settings/settings.css');
</style>

<style lang="scss" scoped>
	.apply {
		.apply-img {
			// width: 86rpx;
			width: 96rpx;
			height: 28rpx;
			margin-right: 5rpx;
		}
	}

	.avatar_box {
		width: 170rpx;
		height: 170rpx;
		 margin: -70rpx auto 25rpx;
		//margin: 60rpx auto 85rpx;
		position: relative;

		.avatar {
			width: 180rpx;
			height: 180rpx;
			border-radius: 50%;
		}

		.change_btn {
			// width: 27rpx;
			// height: 25rpx;
			width: 40rpx;
			height: 40rpx;
			position: absolute;
			right: 10rpx;
			bottom: 10rpx;
			z-index: 1;
		}

		.avatar_img {
			width: 170rpx;
			height: 170rpx;
			display: block;
			border-radius: 50%;
		}

		.tip {
			text-align: center;
			font-size: 24rpx;
			color: #863A3A;
			margin-top: 10rpx;
		}
	}

	.settings_name {
		font-size: 24rpx;
	}

	.value {
		font-size: 24rpx;
		text-align: right;
	}

	.text {
		display: flex;
		align-items: center;

		image {
			width: 23rpx;
			height: 23rpx;
			display: block;
			margin-left: 10rpx;
		}
	}

	.code {
		width: 406rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		text-align: right;

		text {
			font-size: 24rpx;
			font-weight: bold;
		}
	}

	.cont-box {
		z-index: 2;
		padding: 10rpx 30rpx;
		// background-color: $bg-box;
		border-radius: 20rpx;
		position: relative;
	}

	.logout {
		width: 650rpx;
	    height: 90rpx;
		// background-color: #FFE4E8;
		// background-color: var(--QianmenonlyBackgournd);
		border-radius: 45rpx;
		// border: 1px solid #FE005A;
		// border: var(--borderSty);
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		// color: #FE005A;
		color: #ffffff;
		font-weight: 400;
		position: fixed;
		left: 50%;
		bottom: 50rpx;
		z-index: 2;
		transform: translateX(-50%);
	}
</style>
